package net.jonbuck.tassoo.model.util;

import java.net.MalformedURLException;
import java.net.URL;

import net.jonbuck.tassoo.model.provider.TassooEditPlugin;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

/**
 * 
 * 
 * @since 1.0.0
 */
public class ApplicationImages {

	private static ImageRegistry imageRegistry;

	private static final URL baseURL = TassooEditPlugin.INSTANCE.getBaseURL(); //$NON-NLS-1$
	
	/**
	 * Creates a new Image Registry if the internal instance does not exist.
	 * 
	 * @return imageRegistry the internal instance of the image registry.
	 */
	private static ImageRegistry getImageRegistry() {
		if (ApplicationImages.imageRegistry == null) {
			ApplicationImages.imageRegistry = new ImageRegistry();
		}
		return ApplicationImages.imageRegistry;
	}

	/**
	 * Lazily initialises image map.
	 * 
	 * @param imageDescriptor
	 *            The Image descriptor as created within this class.
	 * @return Image the image from the Image Registry
	 */
	public static Image getImage(final String imageLocation) {
		ImageRegistry imageRegistry = getImageRegistry();
		Image image = imageRegistry.get(imageLocation);
		if (image == null) {
			ImageDescriptor imageDescriptor = create(imageLocation);
			ImageData currentImage = imageDescriptor.getImageData();
			int whitePixel = currentImage.palette.getPixel(new RGB(255, 255, 255));
			currentImage.transparentPixel = whitePixel;
			image = new Image(Display.getDefault(), currentImage, currentImage.getTransparencyMask());
			imageRegistry.put(imageLocation, image);
		}
		return image;
	}

	private static ImageDescriptor create(String imageLocation) {
		try {
			if (ApplicationImages.baseURL == null) {
				throw new MalformedURLException();
			}
			return ImageDescriptor.createFromURL(new URL(ApplicationImages.baseURL, imageLocation));
		} catch (MalformedURLException e) {
			return ImageDescriptor.getMissingImageDescriptor();
		}
	}
	
}
